<template>
     <div>
        <!-- <h5>{{str1}} 与 {{str2}} 相似度检测为：</h5> -->
        <textarea ref="string1" placeholder="请输入测试文本1" v-on:input="autoTextAreaHeight" v-model="str1"></textarea>
        <textarea ref="string2"  placeholder="请输入测试文本2" v-on:input="autoTextAreaHeight" v-model="str2"></textarea>
        <h5>相似度检测为：</h5>
        <p >{{rate}}</p>
     </div>
</template>
<style lang="scss" scoped>
 *{
    box-sizing: border-box;
  }
  ul li {
    list-style: none;
  }
 
</style>
<script>
  export default {
    name: 'EditDistance',
    props: {
    },
    data() {
      return {
        rate: '',
        str1:'',
        str2: '',
      }
    },
    components: {

    },
    created() {
    },
    mounted() {
    },
    methods: {
        minDistance(s1,s2) {    
            const len1 = s1.length;
            const len2 = s2.length;
            let matrix = [];
            for(let i = 0; i <= len1; i++) {               //核心算法最小编辑距离
                matrix[i] = new Array();
                for( let j = 0; j <= len2; j++) {
                    if(i ==0 ) {
                        matrix[i][j] = j;
                    } else if(j == 0) {
                        matrix[i][j] = i;
                    } else {
                        let cost = 0;
                        if(s1[i-1] != s2[j-1]) {   // 相同为0，不同置1
                            cost = 1;
                        }
                        const temp = matrix[i-1][j-1] + cost;
                        matrix[i][j] = Math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1,temp);
                    }
                }
            }
            let rate = ((1- matrix[len1][len2] / (Math.max(len1,len2))) * 100).toFixed(2) + '%';
            return rate;
        },
        autoTextAreaHeight:function(e){
            // let o = e.target;
            // o.style.height = o.scrollTop + o.scrollHeight + "px";
        }
       
    },
    watch: {
        str1: function() {
            this.str1 = this.$refs.string1.value;
            console.log(this.str1,'str1');
            if(this.str1 != '' && this.str2 != '') {
                this.rate = this.minDistance(this.str1,this.str2);
            }
        },
        str2: function() {
            this.str2 = this.$refs.string2.value;
             console.log(this.str2,'str2');
             if(this.str1 != '' && this.str2 != '') {
                this.rate = this.minDistance(this.str1,this.str2);
            }
        }
    }
  }
</script>
<style>
  
</style>